#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import os
from sicut.service.AbsRequestCallCppAPI import AbsRequestCallCppAPI
from sicut.BizConstants import BizConstants

class RequestSiCutAPI(AbsRequestCallCppAPI):
    """

    """

    def __init__(self, p_mat_no=None, p_json_template_object=BizConstants.create_playload_sicut()):
        """

        :param p_mat_no:
        :param p_json_template_object:
        """
        super(RequestSiCutAPI, self).__init__(p_mat_no=p_mat_no, p_json_template_object=p_json_template_object)

    def _on_before_request(self, p_payload=None, p_headers=None):
        """

        :return:
        """
        pass

    def _on_request_fail(self, p_exception=None):
        """

        :param p_exception:
        :return:
        """
        self.logger.error('RequestSiCutAPI._on_request_fail---->>\n%s' % (str(p_exception)))
        return False, -1, list()

    def _on_parsing(self, p_payload=None, p_response_dict=None):
        """

        :param p_response_dict:
        :return:
        """
        self.logger.info('RequestSiCutAPI._on_parsing')

        columns = p_response_dict['Tables'][0]['Columns']
        rows = p_response_dict['Tables'][0]['Rows']

        # NOTE 第一种情况
        # OUT_MAT_NO  "11849344820", 第9列， index=8
        index_of_out_mat_no = columns.index(next(x for x in columns if x['Name'] == 'OUT_MAT_NO'))
        target_row = next(x for x in rows if x[index_of_out_mat_no] == self.mat_no)

        # MAT_ACT_WIDTH  第18个， index=17 ----》1092
        index_of_mat_act_width = columns.index(next(x for x in columns if x['Name'] == 'MAT_ACT_WIDTH'))
        v = target_row[index_of_mat_act_width]
        self.logger.info('p_mat_no=%s, MAT_ACT_WIDTH=%s---->>>' % (self.mat_no, v))

        # NOTE 第二种情况
        index_of_in_mat_no_1 = columns.index(next(x for x in columns if x['Name'] == 'IN_MAT_NO_1'))
        target_sub_out_mat_no = list()
        for r in rows:
            if r[index_of_in_mat_no_1] == self.mat_no:
                tmp = r[index_of_out_mat_no]
                target_sub_out_mat_no.append(tmp)
        self.logger.info('p_mat_no=%s, MAT_ACT_WIDTH=%s---->>>' % (self.mat_no, ','.join(target_sub_out_mat_no)))

        return True, v, target_sub_out_mat_no

    def _on_parse_fail(self, p_response=None, p_exception=None):
        """

        :param p_exception:
        :return:
        """
        self.logger.error('RequestSiCutAPI._on_parse_fail---->>\n%s' % (str(p_exception)))
        return False, -1, list()
